import { useEffect, useRef, useState } from 'react'
import { Button, Empty, Form, Input, Modal, Space, Table, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { observer } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';
import { InbizIcon } from '@inbiz/utils'
import { deleteDataPermModule, deleteDataPermRule, getDPModule, getDataPermRule, statusChange, updateDPModule } from '../service';
import RoleConfig from './RoleConfig';
import './index.less'

const DataPermission = (props: any) => {
  const { appId } = props
  // 分组搜索文本
  const [searchGroupIpts, $searchGroupIpts] = useState<string>('')
  // 分组搜索-搜索文本
  const [searchGroupTxt, $searchGroupTxt] = useState<string>('')
  // 分组数据
  const [groupData, $groupData] = useState<any[]>([])
  // 当前选中分组
  const [activeGroup, $activeGroup] = useState<string>('')
  // 当前编辑分组数据
  const [editGroupData, $editGroupData] = useState<any>()
  // 模块弹窗显示
  const [groupVisible, $groupVisible] = useState<boolean>(false)
  // 权限选中key
  const [selectedRowKeys, $selectedRowKeys] = useState<string[]>([])
  // 权限弹窗是否是修改
  const [isEdit, $isEdit] = useState(false)
  // 当前修改权限数据
  const [currentItem, $currentItem] = useState(null)
  // 权限弹窗显示
  const [visible, $visible] = useState(false)
  // 权限数据当前页码
  const [pageIndex, $pageIndex] = useState<number>(1)
  // 权限数据单页数量
  const [pageSize, $pageSize] = useState<number>(10)
  // 权限数据
  const [list, $list] = useState([])
  // 权限数据总量
  const [total, $total] = useState<number>(0)
  // 权限数据搜索框文本
  const [searchPermIpts, $searchPermIpts] = useState<string>('')
  // 权限数据搜索文本
  const [keyWords, $keyWords] = useState('')
  // 保存模块loading
  const [updateModuleLoading, $updateModuleLoading] = useState<boolean>(false)
  // 分组搜索input
  const searchGroupRef = useRef<any>()
  // 权限搜索input
  const searchPermRef = useRef<any>()
  // 模块表单
  const [groupForm] = Form.useForm()

  // 初始化
  useEffect(() => {
    getModuleList()
  }, [])

  // 分组变化
  useEffect(() => {
    $searchPermIpts('')
    $keyWords('')
    $selectedRowKeys([])
    if (pageIndex === 1) {
      getPermissionList(1, '');
    } else {
      $pageIndex(1)
    }
  }, [activeGroup])

  // 分页数据变化
  useEffect(() => {
    getPermissionList();
  }, [pageIndex, pageSize]);

  // 获取模块列表数据
  const getModuleList = (pick?: string | boolean) => {
    getDPModule().then((res: any) => {
      if (Array.isArray(res)) {
        $groupData(res)
        if (activeGroup == '' && res.length > 0 || pick === true) {
          $activeGroup(res[0].Id)
        } else if (typeof (pick) === 'string' && pick !== '') {
          $activeGroup(pick)
        }
      } else {
        $groupData([])
        $activeGroup('')
      }
    })
  }

  // 分组搜索
  const searchGroup = (val: string) => {
    $searchGroupTxt(val)
  }

  // 新建/编辑模块表单提交
  const groupSubmit = () => {
    $updateModuleLoading(true)
    groupForm.validateFields().then((res: any) => {
      const obj = {
        id: editGroupData?.Id,
        name: res.Name,
      }
      updateDPModule(obj).then((res: any) => {
        if (res) {
          message.success(<TextWidget>{editGroupData?.Id ? 'Permission.perm_edit_modu_mess' : 'Permission.perm_add_modu_mess'}</TextWidget>) // 新增模块成功 || 编辑模块成功
          getModuleList(editGroupData?.Id ? false : res)
          $groupVisible(false)
          $editGroupData(null)
        }
        $updateModuleLoading(false)
      })
    }).catch(() => {
      $updateModuleLoading(false)
    })
  }

  // 编辑模块
  const editGroup = (e: any, rec: any) => {
    e.stopPropagation()
    $editGroupData(rec)
    $groupVisible(true)
    groupForm.setFieldsValue(rec)
  }

  // 新增模块
  const addGroup = () => {
    $groupVisible(true)
    groupForm.setFieldsValue({ Name: '' })
  }

  // 删除模块
  const delGroup = (e: any, rec: any) => {
    e.stopPropagation()
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: <TextWidget>Permission.warning</TextWidget>, // 警告
      content: <TextWidget>Permission.perm_del_modu_warn</TextWidget>, // 删除后将解除所有权限验证，确认删除此模块吗？
      okText: <TextWidget>global.sure</TextWidget>, // 确定
      cancelText: <TextWidget>global.cancel</TextWidget>, // 取消
      onOk: () => {
        deleteDataPermModule({
          id: rec.Id,
        }).then(res => {
          if (!res) return;
          message.success(<TextWidget>Permission.perm_del_modu_succ</TextWidget>); // 模块删除成功
          if (rec.Id == activeGroup) {
            $activeGroup('')
            getModuleList(true);
          } else {
            getModuleList();
          }
        });
      },
    });
  }

  // 获取权限列表
  const getPermissionList = (page?: number, key?: string) => {
    if (activeGroup === '') return
    getDataPermRule({
      moduleId: activeGroup,
      keyWords: key ?? keyWords,
      skipCount: ((page ?? pageIndex) - 1) * pageSize,
      maxResultCount: pageSize,
    }).then(res => {
      if (!res) return;
      $list(res.Items);
      $total(res.TotalCount)
    });
  };

  // 权限搜索
  const searchPerm = (val: string) => {
    $keyWords(val)
    if (pageIndex == 1) {
      getPermissionList(1, val)
    }
    else {
      $pageIndex(1)
    }
  }

  // 新增权限
  const onAdd = () => {
    $currentItem(null);
    $isEdit(false);
    $visible(true);
  };

  // 编辑
  const onEdit = (record: any) => {
    $currentItem(record);
    $isEdit(true);
    $visible(true);
  };

  // 多个/单个 => 删除
  const onDelete = (stateStr: string, record?: any) => {
    Modal.confirm({
      title: <TextWidget>Permission.warning</TextWidget>, // 警告
      content: <TextWidget>Permission.del_perm_mess</TextWidget>, // 删除后将解除所有权限验证，确认删除此规则吗
      okText: <TextWidget>global.sure</TextWidget>, // 确定
      cancelText: <TextWidget>global.cancel</TextWidget>, // 取消
      onOk() {
        deleteDataPermRule({
          idList: stateStr === 'batch' ? [...selectedRowKeys] : [record.Id], // 批量删除 or 单个删除
        }).then((res: any) => {
          if (!res) return;
          // 批量删除需要初始化选中项
          if (stateStr == 'batch') {
            $selectedRowKeys([])
          }
          else {
            let index = selectedRowKeys.findIndex(selected => selected == record.Id);
            if (index >= 0) {
              $selectedRowKeys(data => {
                data.splice(index, 1);
                return data;
              })
            }
          }
          message.success(<TextWidget>Permission.perm_del_perm_succ</TextWidget>); // 规则删除成功
          getPermissionList();
        });
      },
    });
  };

  // 多个/单个 => 启用、停用
  const onStatusChange = (stateStr: string, record?: any) => {
    statusChange({
      idList: stateStr === 'batch' ? [...selectedRowKeys] : [record.Id],
      status: record.Status == 1 ? '0' : '1',
    }).then(res => {
      if (!res) return;
      if (record.Status == 1) {
        message.success(<TextWidget>Permission.perm_start_mess</TextWidget>); // 规则启用成功
      } else {
        message.success(<TextWidget>Permission.perm_stop_mess</TextWidget>); // 规则停用成功
      }
      getPermissionList();
    });
  };

  // 表格列配置
  const columns = [
    {
      title: getMessage('Permission.perm_name'), // 权限规则名称
      dataIndex: 'Name',
      key: 'Name',
      ellipsis: true,
    },
    {
      title: getMessage('Permission.type'), // 类型
      dataIndex: 'Type',
      key: 'Type',
      ellipsis: true,
      render: (val: number) => <span>{val == 1 ? getMessage('Permission.perm_search') : getMessage('Permission.perm_model')}</span>, // '查询器' : '模型'
    },
    {
      title: getMessage('Permission.name'), // 名称
      dataIndex: 'TypeName',
      key: 'TypeName',
      ellipsis: true,
    },
    {
      title: getMessage('Permission.perm_status'), // 状态
      dataIndex: 'Status',
      key: 'Status',
      ellipsis: true,
      render: (val: number) => <span>{val == 1 ? getMessage('Permission.perm_stoped') : getMessage('Permission.perm_running')}</span>, // '已停用' : '启用中'
    },
    {
      title: getMessage('Permission.perm_mark'), // 权限说明
      dataIndex: 'Remark',
      key: 'Remark',
      width: '24%',
      ellipsis: true,
    },
    {
      title: getMessage('Permission.perm_handle'), // 操作
      dataIndex: 'action',
      key: 'action',
      // width: 180,
      render: (_: any, record: { Status: number; }) => (
        <>
          <Button size="small" type={'link'} onClick={() => onEdit(record)}>
            <TextWidget>Permission.edit</TextWidget>{/* 编辑 */}
          </Button>
          <Button size="small" type={'link'} onClick={() => onDelete('single', record)}>
            <TextWidget>Permission.delete</TextWidget>{/* 删除 */}
          </Button>
          <Button size="small" type={'link'} onClick={() => onStatusChange('single', record)}>
            {record.Status == 1 ?
              <TextWidget>Permission.start</TextWidget> // '启用' 
              : <TextWidget>Permission.stop</TextWidget> // '停用'
            }
          </Button>
        </>
      ),
    },
  ];

  // 表格props
  const tableProps = {
    dataSource: list,
    className: list.length > 0 ? '' : 'table-no-data',
    columns,
    bordered: true,
    rowKey: 'Id',
    rowSelection: {
      onChange: (selectedRowKeys: any[]) => {
        $selectedRowKeys(selectedRowKeys);
      },
      selectedRowKeys: selectedRowKeys,
    },
    pagination: {
      pageSize,
      total,
      current: pageIndex,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '30', '50', '100'],
      // @ts-ignore
      showTotal: true,
      onChange: (current: number, pageSize: number) => {
        $pageIndex(current);
        $pageSize(pageSize);
      },
      onShowSizeChange: (current: number, pageSize: number) => {
        $pageIndex(current);
        $pageSize(pageSize);
      },
    },
    // loading: {loading.effects['permissionFun/getDataPermRule']}
    scroll: { y: 620, scrollToFirstRowOnChange: true }
  };

  // 权限配置props
  const roleConfigProps = {
    visible,
    isEdit,
    appId,
    currentItem,
    currentModule: activeGroup,
    onCancel: () => $visible(false),
    onSuccess: () => {
      $visible(false);
      getPermissionList();
    },
  };

  return (
    <div className='inbiz-comp-permission-data'>
      {/* 左侧分组 */}
      <div className='left-group'>
        {/* Title */}
        <div className='title-box'>
          <p><TextWidget>Permission.modulel_list</TextWidget></p>
          <span onClick={addGroup}><InbizIcon type='icon-ic-tianjia-moren' style={{ marginRight: 5 }} /><TextWidget>Permission.add</TextWidget></span>
        </div>
        {/* 分组搜索 */}
        <Input
          ref={searchGroupRef}
          value={searchGroupIpts}
          onPressEnter={(e: any) => {
            searchGroup(e.target.value);
          }}
          onChange={(e) => $searchGroupIpts(e.target.value)}
          placeholder={getMessage('Permission.module_placeholder')}
          style={{ marginRight: 10 }}
          suffix={
            <InbizIcon
              type="icon-ic-sousuo"
              style={{ color: '#999' }}
              onClick={() => {
                searchGroup(searchGroupRef.current?.input?.value || '');
              }}
            />
          }
        />
        {/* 分组列表 */}
        <div className='list-gourp'>
          {
            groupData?.filter((i: any) => i.Name.indexOf(searchGroupTxt) > -1)?.length ?
              groupData.filter((i: any) => i.Name.indexOf(searchGroupTxt) > -1).map((item: any) => {
                return (
                  <div
                    className={activeGroup === item.Id ? 'list-group-item list-group-item-active' : 'list-group-item'}
                    onClick={() => {
                      $activeGroup(item.Id)
                    }}
                  >
                    <span className='item-name'>{item.Name}</span>
                    <InbizIcon
                      type="icon-ic-bianjituandui"
                      onClick={(e: any) => editGroup(e, item)}
                      title={getMessage('Permission.edit')}
                    />
                    <InbizIcon
                      type="icon-ic-tree-huishouzhan"
                      onClick={(e: any) => delGroup(e, item)}
                      title={getMessage('Permission.delete')}
                    />
                  </div>
                )
              }) : <Empty
                image={null}
                style={{
                  height: 'calc(100vh - 278px)',
                  display: 'flex',
                  paddingBottom: 50,
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: 'rgba(0,0,0,.25)'
                }}
              />
          }
        </div>
      </div>
      {/* 右侧表格 */}
      <div className='permision-right'>
        <div className='permision-right-header'>
          <Space>
            <Button
              type='primary'
              onClick={onAdd}
              disabled={!activeGroup}
            >
              <TextWidget>Permission.add_permision</TextWidget>
            </Button>

            <Button
              danger
              onClick={() => onDelete('batch')}
              disabled={selectedRowKeys.length == 0}
            >
              <TextWidget>Permission.delete</TextWidget>
            </Button>

            <Button
              onClick={() => onStatusChange('batch', { Status: 1 })}
              disabled={selectedRowKeys.length == 0}
            >
              <TextWidget>Permission.start</TextWidget>
            </Button>

            <Button
              onClick={() => onStatusChange('batch', { Status: 0 })}
              disabled={selectedRowKeys.length == 0}
            >
              <TextWidget>Permission.stop</TextWidget>
            </Button>
          </Space>
          {/* 权限搜索 */}
          <Input
            ref={searchPermRef}
            value={searchPermIpts}
            onPressEnter={(e: any) => {
              searchPerm(e.target.value);
            }}
            onChange={(e) => $searchPermIpts(e.target.value)}
            placeholder={getMessage('Permission.perm_search_placeholder')}
            style={{ width: 260 }}
            suffix={
              <InbizIcon
                type="icon-ic-sousuo"
                style={{ color: '#999' }}
                onClick={() => {
                  searchPerm(searchPermRef.current?.input?.value || '');
                }}
              />
            }
          />
        </div>
        <Table {...tableProps} />
      </div>

      {/* 新建/编辑模块Modal */}
      <Modal
        title={editGroupData ?
          <TextWidget>Permission.perm_edit_modu</TextWidget> // 编辑模块
          : <TextWidget>Permission.perm_add_modu</TextWidget> // 新建模块
        }
        visible={groupVisible}
        onCancel={() => {
          $editGroupData(null)
          $groupVisible(false)
          $updateModuleLoading(false)
        }}
        onOk={groupSubmit}
        confirmLoading={updateModuleLoading}
      >
        <Form form={groupForm} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }}>
          <Form.Item
            name='Name'
            label={<TextWidget>Permission.perm_modu_name</TextWidget>} // 模块名称
            rules={[
              { required: true, message: getMessage('Permission.perm_modu_name_null') },
              { message: getMessage('Permission.perm_modu_name_err'), pattern: /^[^%#&',;=?$\x22]*$/g },
              { max: 50, message: getMessage('Permission.perm_modu_name_max') }
            ]}
            style={{ marginTop: 20 }}
          >
            <Input placeholder={getMessage('Permission.perm_modu_name_plac')} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限配置弹窗 */}
      {visible && <RoleConfig {...roleConfigProps} />}
    </div>
  )
}

export default observer(DataPermission)